<?php
/**
 * 所有的公共函数
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-09-01
 * Time: 14:56
 */

function nonceStr($length = 8)
{
// 密码字符集，可任意添加你需要的字符
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $nonceStr = '';
    for ($i = 0; $i < $length; $i++) {
        $nonceStr .= $chars[mt_rand(0, strlen($chars) - 1)];
    }
    return $nonceStr;
}
function nonceStrBig($length = 8)
{
// 密码字符集，可任意添加你需要的字符
    $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
    $nonceStr = '';
    for ($i = 0; $i < $length; $i++) {
        $nonceStr .= $chars[mt_rand(0, strlen($chars) - 1)];
    }
    return $nonceStr;
}
//将XML转为array
function xmlToArray($xml)
{
    //禁止引用外部xml实体
    libxml_disable_entity_loader(true);
    $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $values;
}

/**
 * 获取客户端IP
 * @return array|false|string
 */
function getIp()
{
    if (getenv('HTTP_CLIENT_IP')) {
        $onlineip = getenv('HTTP_CLIENT_IP');
    } elseif (getenv('HTTP_X_FORWARDED_FOR')) {
        $onlineip = getenv('HTTP_X_FORWARDED_FOR');
    } elseif (getenv('REMOTE_ADDR')) {
        $onlineip = getenv('REMOTE_ADDR');
    } else {
        $onlineip = "127.0.0.1";
    }
    return $onlineip;
}

function path($pic)
{
    if(empty($pic)){
        $pic = "";
    }else{
        $http = substr($pic,0,4);
        if($http != 'http'){
            $pic = "https://oss.xmw1688.com" . $pic;
        }
    }
    return $pic;
}

/**
 * 获取订单编号
 * @param $type
 * @return string
 */
function getOrderSn($type)
{
    $orderSn = $type
        . sprintf('%010d', time() - 946656000)
        . sprintf('%03d', (float)microtime() * 1000)
        . mt_rand(1000, 9999);

    return $orderSn;
}

/**
 * 得到支付宝支付配置
 * @return array
 */
function getAliConfig()
{
    $config = array(
        //应用ID,您的APPID。
        'app_id' => env("ALI_APPID"),

        //商户私钥
        'merchant_private_key' => env("ALI_MERCHANT_PRIVATE_KEY"),
        //异步通知地址
        'notify_url' => env("ALI_NOTIFY_URL"),

        //同步跳转
        'return_url' => env("ALI_NOTIFY_URL"),

        //编码格式
        'charset' => env("ALI_CHARSET"),

        //签名方式
        'sign_type' => env("ALI_SIGN_TYPE"),

        //支付宝网关
        'gatewayUrl' => env("ALI_GATEWAYURL"),

        //支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
        'alipay_public_key' => env("ALI_PAY_PUBLIC_KEY")
    );
    return $config;
}

//获取毫秒
function msectime()
{
    list($msec, $sec) = explode(' ', microtime());
    $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);

    return $msectime;
}

/**
 * 获得上个月日期
 * @param $date 2017-09-11
 * @return array
 */
function getlastMonthDays($date)
{
    $timestamp = strtotime($date);
    $firstday = date('Y-m-01', strtotime(date('Y', $timestamp) . '-' . (date('m', $timestamp) - 1) . '-01'));
    $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
    return array($firstday, $lastday);
}

function birthday($birthday)
{
    $age = strtotime($birthday);
    if ($age === false) {
        return false;
    }
    list($y1, $m1, $d1) = explode("-", date("Y-m-d", $age));
    $now = strtotime("now");
    list($y2, $m2, $d2) = explode("-", date("Y-m-d", $now));
    $age = $y2 - $y1;
    if ((int)($m2 . $d2) < (int)($m1 . $d1))
        $age -= 1;
    return $age;
}

/**
 * 数组转对象
 * @param $array
 * @return StdClass
 */
function array2object($array)
{
    if (is_array($array)) {
        $obj = new StdClass();
        foreach ($array as $key => $val) {
            $obj->$key = $val;
        }
    } else {
        $obj = $array;
    }
    return $obj;
}

/**
 * 对象转数组
 * @param $object
 * @return mixed
 */
function object2array($object)
{
    if (is_object($object)) {
        foreach ($object as $key => $value) {
            $array[$key] = $value;
        }
    } else {
        $array = $object;
    }
    return $array;
}

function _ksort($arr, $key, $order = 'desc')
{
    if (!is_array($arr)) return false;

    array_values($arr);
    foreach ($arr as $k => $v) {
        $ks = (string)$v[$key];
        if (isset($array[$ks])) {
            $array[$ks . '.' . $k] = $array[$ks];
            $array[$ks . '.' . ($k + 1)] = $v;
            unset($array[$ks]);
            continue;
        }
        $array[$ks] = $v;
    }
    if ($order == 'asc') {
        ksort($array);
    } elseif ($order == 'desc') {
        krsort($array);
    }

    foreach ($array as $v) {
        $return[] = $v;
    }
    return $return;
}

/**
 * 根据起点坐标和终点坐标测距离
 * @param  [array]   $from    [起点坐标(经纬度),例如:array(118.012951,36.810024)]
 * @param  [array]   $to    [终点坐标(经纬度)]
 * @param  [bool]    $km        是否以公里为单位 false:米 true:公里(千米)
 * @param  [int]     $decimal   精度 保留小数位数
 * @return [string]  距离数值
 */
function get_distance($from, $to, $km = false, $decimal = 2)
{
    sort($from);
    sort($to);
    $EARTH_RADIUS = 6370.996; // 地球半径系数

    $distance = $EARTH_RADIUS * 2 * asin(sqrt(pow(sin(($from[0] * pi() / 180 - $to[0] * pi() / 180) / 2), 2) + cos($from[0] * pi() / 180) * cos($to[0] * pi() / 180) * pow(sin(($from[1] * pi() / 180 - $to[1] * pi() / 180) / 2), 2))) * 1000;

    if ($km) {
        $distance = $distance / 1000;
    }

    return round($distance, $decimal);
}

//多维数组排序
function my_array_multisort($data, $sort_order_field, $sort_order = SORT_ASC, $sort_type = SORT_NUMERIC)
{
    foreach ($data as $val) {
        $key_arrays[] = $val[$sort_order_field];
    }
    array_multisort($key_arrays, $sort_order, SORT_NUMERIC, $data);
    return $data;
}

function getFirstCharter($str)
{
    if (empty($str)) {
        return '';
    }
    $fchar = ord($str[0]);
    if ($fchar >= ord('A') && $fchar <= ord('z'))
        return strtoupper($str[0]);
    $s1 = iconv('UTF-8', 'gb2312', $str);
    $s2 = iconv('gb2312', 'UTF-8', $s1);
    $s = $s2 == $str ? $s1 : $str;
    $asc = ord($s[0]) * 256 + ord($s[1]) - 65536;
    if ($asc >= -20319 && $asc <= -20284)
        return 'A';
    if ($asc >= -20283 && $asc <= -19776)
        return 'B';
    if ($asc >= -19775 && $asc <= -19219)
        return 'C';
    if ($asc >= -19218 && $asc <= -18711)
        return 'D';
    if ($asc >= -18710 && $asc <= -18527)
        return 'E';
    if ($asc >= -18526 && $asc <= -18240)
        return 'F';
    if ($asc >= -18239 && $asc <= -17923)
        return 'G';
    if ($asc >= -17922 && $asc <= -17418)
        return 'H';
    if ($asc >= -17417 && $asc <= -16475)
        return 'J';
    if ($asc >= -16474 && $asc <= -16213)
        return 'K';
    if ($asc >= -16212 && $asc <= -15641)
        return 'L';
    if ($asc >= -15640 && $asc <= -15166)
        return 'M';
    if ($asc >= -15165 && $asc <= -14923)
        return 'N';
    if ($asc >= -14922 && $asc <= -14915)
        return 'O';
    if ($asc >= -14914 && $asc <= -14631)
        return 'P';
    if ($asc >= -14630 && $asc <= -14150)
        return 'Q';
    if ($asc >= -14149 && $asc <= -14091)
        return 'R';
    if ($asc >= -14090 && $asc <= -13319)
        return 'S';
    if ($asc >= -13318 && $asc <= -12839)
        return 'T';
    if ($asc >= -12838 && $asc <= -12557)
        return 'W';
    if ($asc >= -12556 && $asc <= -11848)
        return 'X';
    if ($asc >= -11847 && $asc <= -11056)
        return 'Y';
    if ($asc >= -11055 && $asc <= -10247)
        return 'Z';
    return null;
}

function GetCharactors($samples, $levels, $times, $result = array())
{
    $temp = array();
    for ($i = 0; $i < $times; $i++) {
        $temp[] = array_shift($samples);
    }
    $result[$levels] = implode('', $temp);
    $levels--;
    if ($levels > 0) {
        shuffle($samples);
        $result = GetCharactors($samples, $levels, $times, $result);
    }
    return $result;
}

function object_array($array)
{
    if (is_object($array)) {
        $array = (array)$array;
    }
    if (is_array($array)) {
        foreach ($array as $key => $value) {
            $array[$key] = object_array($value);
        }
    }
    return $array;
}

function order_number($openid)
{
    return md5($openid . time() . rand(10, 99));//32位
}

function orderNo()
{
    return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}

function label($label)
{
    $res = [];
    $i = 0;
    $res[$i]['num'] = 0;

    $abc = \App\Models\LabelSetting::select()->get()->toArray();
    foreach ($label as $kk => $vvv) {
        foreach ($abc as $key => $vv) {
            $cbs = json_decode($vvv['label']);
            foreach ($cbs as $k => $v) {

                if ($v == $vv['contentLabel']) {
                    $res[$i] = $vv['contentLabel'];
                    $i++;
                }


            }

        }
    }

    $res = array_count_values($res);
    return $res;
}

/**
 *      *计算某个经纬度的周围某段距离的正方形的四个点
 *      *@param lng float 经度
 *      *@param lat float 纬度
 *      *@param distance float 该点所在圆的半径，该圆与此正方形内切，默认值为0.5千米
 *      *@return array 正方形的四个点的经纬度坐标
 *      */
function returnSquarePoint($lng, $lat, $distance = 5)
{
    $earthdata = 6371;//地球半径，平均半径为6371km
    $dlng = 2 * asin(sin($distance / (2 * $earthdata)) / cos(deg2rad($lat)));
    $dlng = rad2deg($dlng);
    $dlat = $distance / $earthdata;
    $dlat = rad2deg($dlat);
    $arr = array(
        'left_top' => array('lat' => $lat + $dlat, 'lng' => $lng - $dlng),
        'right_top' => array('lat' => $lat + $dlat, 'lng' => $lng + $dlng),
        'left_bottom' => array('lat' => $lat - $dlat, 'lng' => $lng - $dlng),
        'right_bottom' => array('lat' => $lat - $dlat, 'lng' => $lng + $dlng)
    );
    return $arr;
}

//时间转换

function turnTime($targetTime)
{
    $targetTime = strtotime($targetTime);
    $todayLast = strtotime(date('Y-m-d 23:59:59'));
    $agoTimeTrue = time() - $targetTime;
    $agoTime = $todayLast - $targetTime;
    $agoDay = floor($agoTime / 86400);
    if ($agoTimeTrue < 60) {
        $result = '刚刚';
    } elseif ($agoTimeTrue < 3600) {
        $result = (ceil($agoTimeTrue / 60)) . '分钟前';
    } elseif ($agoTimeTrue < 3600 * 12) {
        $result = (ceil($agoTimeTrue / 3600)) . '小时前';
    } elseif ($agoDay == 0) {
        $result = '今天 ' . date('H:i', $targetTime);
    } elseif ($agoDay == 1) {
        $result = '昨天 ' . date('H:i', $targetTime);
    } elseif ($agoDay == 2) {
        $result = '前天 ' . date('H:i', $targetTime);
    } elseif ($agoDay > 2 && $agoDay < 16) {
        $result = $agoDay . '天前 ' . date('H:i', $targetTime);
    } else {
        $format = date('Y') != date('Y', $targetTime) ? "Y-m-d H:i" : "m-d H:i";
        $result = date($format, $targetTime);
    }
    return $result;
}

//数组转为xml
function create($ar, $xml)
{
    foreach ($ar as $k => $v) {
        if (is_array($v)) {
            $x = $xml->addChild($k);
            create($v, $x);
        } else $xml->addChild($k, $v);
    }
}

function getWeek($num)
{
    return str_replace([0, 1, 2, 3, 4, 5, 6], ["周一", "周二", "周三", "周四", "周五", "周六", "周日"], $num);
}

function getthemonth($date)
{
    $firstday = date('Y-m-01', strtotime($date));
    $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
    return array($firstday, $lastday);
}

function convertTime($num)
{
    $xiaoshi = floor($num / 60);    //取小时

    if ($num % 60 == 0) {   //表示可以被60整除，没有分钟
        $fenzhong = 0;
    } else {               //不可以被60整除，有分钟，获取这个分钟数
        $fenzhong = $num % 60;
    }

    if ($xiaoshi == 0) {
        return $fenzhong . '分';
    } elseif ($xiaoshi != 0 && $fenzhong == 0) {
        return $xiaoshi . '时';
    } elseif ($xiaoshi != 0 && $fenzhong != 0) {
        return $xiaoshi . '时' . $fenzhong . '分';
    }
}

function ip2area($ip) {
    $area = '';
    if (is_ip($ip)) {
        $tmp = explode('.', $ip);
        if ($tmp[0] == 10 || $tmp[0] == 127 || ($tmp[0] == 192 && $tmp[1] == 168) || ($tmp[0] == 172 && ($tmp[1] >= 16 && $tmp[1] <= 31))) {
            $area = 'LAN';
        } elseif ($tmp[0] > 255 || $tmp[1] > 255 || $tmp[2] > 255 || $tmp[3] > 255) {
            $area = 'Unknown';
        } else {
            $ipfile = "/home/wwwroot/dewen_laravel_service/app/Libs/Common/ipdata/";
            require_once 'ip.class.php';
            $do = new ip($ip);
            $area = $do->area($ipfile);
        }
    }
    return $area ? $area : 'Unknown';
}

function is_ip($ip) {
    return preg_match("/^([0-9]{1,3}\.){3}[0-9]{1,3}$/", $ip);
}

